//
//  TFHornView.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/4/21.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TFHornView: UIView {

    @objc public let hornButton = UIButton()
    @objc public let closeButton = UIButton()

    @objc public var link:NSString = ""
    @objc public let content = UILabel()
    @objc public weak var delegate : TFHornViewDelegate?
    var basicAni:CABasicAnimation?
    let view = UIView()
    var duration:NSInteger = 0
    @objc public var timer : Timer?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor(red: 255/255.0, green: 240/255.0, blue: 212/255.0, alpha: 1)
        self.addSubview(self.hornButton)
        
        self.hornButton.setImage(UIImage.init(named: "HTLive.bundle/notice"), for: .normal)
        self.addSubview(self.closeButton)
    
        self.closeButton.setImage(UIImage.init(named: "HTLive.bundle/close_yellow"), for: .normal)
        
        self.closeButton.addTarget(self, action: #selector(self.closeClick), for: .touchUpInside)
        
      
        self.view.clipsToBounds = true
        self.addSubview(self.view)
        
      
        self.view.addSubview(self.content)
        self.content.font = UIFont.PingFang(size: 16)
        
        self.content.textColor = UIColor(red: 112/255.0, green: 53/255.0, blue: 7/255.0, alpha: 1)
        
    }
         
    @objc public func closeClick()
    {
        self.removeFromSuperview()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.hornButton.frame = CGRect(x: 10, y: (self.frame.size.height-25)/2.0, width: 46, height: 25)
       
        self.closeButton.frame = CGRect(x: self.frame.size.width-32-10, y: (self.frame.size.height-40)/2.0, width: 40, height: 40) 
        
         let contentWidth = self.frame.size.width - self.hornButton.frame.maxX - self.closeButton.frame.size.width
        self.view.frame = CGRect(x: self.hornButton.frame.maxX, y: 0, width: contentWidth, height: self.frame.size.height) 
    }

    func timerStop()
    {
        
        if (self.timer != nil) {
            self.timer?.invalidate()
            self.timer = nil
        }
       
    }
  @objc func timer_Action()
    {
        self.duration = self.duration - 1
        if (self.duration <= 0 ) {
          
            self.closeClick()
        }

    }
    @objc public func announceRoll(obj:TFAnnounceRoll)
    {
        if (obj.duration == 0) {
            self.isHidden = true
            return
        }
        let content:NSString = obj.content as NSString
        if (content.length>0) {
            self.isHidden = false
            
            self.link = "";
            
            let link:NSString = obj.link as NSString
            if (link.length>0) {
                self.link = link
            }
            self.duration = 0
           
            self.content.layer.removeAllAnimations()
            self.timerStop()
           
            if (self.duration != 0) {
                
                self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timer_Action), userInfo: nil, repeats: true)
                RunLoop.main.add(self.timer! , forMode: RunLoop.Mode.default)
                self.timer!.fire()
                
            }

            let attrsSize: CGSize = content.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 16)])
            
            var viewWidth:CGFloat = attrsSize.width


            self.content.text = obj.content
            self.content.textAlignment = .left
            
            
            let contentWidth = self.frame.size.width - self.hornButton.frame.maxX - self.closeButton.frame.size.width
            
            var contentX = contentWidth
            if (viewWidth < contentWidth) {
                contentX = 0
                viewWidth = contentWidth
            }
            self.content.frame = CGRect(x: contentX, y: 0, width: viewWidth, height: self.bounds.size.height)
        
            //TFAutoScrollLabel
            if self.content.frame.width > contentWidth {
                self.start_Animation()
            }
        }
    }
    func start_Animation()
    {
        
//    let movePath = UIBezierPath()
//
//    movePath.move(to: CGPoint(x: self.view.frame.width, y: self.content.bounds.size.height/2))
//
//    movePath.addLine(to: CGPoint(x: -self.content.frame.size.width+10, y: self.content.bounds.size.height/2))
//
//    let moveAnimation = CAKeyframeAnimation.init(keyPath: "position")
//
//    moveAnimation.path = movePath.cgPath
//    moveAnimation.isRemovedOnCompletion = false
//
//    moveAnimation.fillMode = kCAFillModeForwards
//
//    let interval:CGFloat = self.content.frame.size.width / 35
//
//    moveAnimation.duration = interval
//
//    moveAnimation.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
//
//    self.content.layer.add(moveAnimation, forKey: "animationViewPosition")
        
        if self.basicAni != nil {
            self.basicAni = nil
        }
     
        //创建动画对象
        let basicAni = CABasicAnimation()
        self.basicAni = basicAni
        //设置动画属性
        basicAni.keyPath = "position";

        //设置动画的起始位置。也就是动画从哪里到哪里
        basicAni.fromValue = NSValue.init(cgPoint: CGPoint(x: self.content.frame.size.width/2+self.view.frame.size.width, y: self.content.frame.size.height/2))

        //动画结束后，layer所在的位置
        basicAni.toValue = NSValue.init(cgPoint: CGPoint(x:-(self.content.frame.size.width/2), y: self.content.frame.size.height/2))
        
     
        //动画持续时间
        basicAni.duration = self.content.frame.size.width/35

        //动画填充模式
        basicAni.fillMode = CAMediaTimingFillMode.forwards

        //动画完成不删除
        basicAni.isRemovedOnCompletion = false


        basicAni.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
        //把动画添加到要作用的Layer上面

        self.content.layer.add(basicAni, forKey: "animationViewPosition")
//        [self.content.layer addAnimation:basicAni forKey:nil];
        

    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
 
        // 重点开始！！UITouch 获取在 barrageView 坐标系下的坐标
        for touch : AnyObject in touches {
            
       let t : UITouch = touch as! UITouch;
            
        let  touchPoint =  t.location(in: self.view)
      
            if ((self.content.layer.presentation()?.hitTest(touchPoint)) != nil) {
                
                if self.delegate != nil && (self.delegate?.responds(to: #selector(TF_AnnounceRollViewDelegate.marqueeClick) )   )!{
                    
                    self.delegate?.marqueeClick()
                    
                }
                return;
            }
 
        }

    }

}
@objc protocol TFHornViewDelegate : NSObjectProtocol {

    func marqueeClick()
}
